package com.china.produce.config.properties;

import com.china.produce.annotation.LoginNeedless;
import com.china.produce.system.util.LoginNeedlessUtils;
import com.china.produce.system.util.RedisUtil;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 获取不要登录接口地址
 *
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/3/7
 */
@Component
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware {


    private ApplicationContext applicationContext;

    private List<String> urls = new ArrayList<>();

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    public String ASTERISK = "*";

    @Override
    public void afterPropertiesSet() throws Exception {

        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

        handlerMethods.keySet().forEach(item -> {
            HandlerMethod handlerMethod = handlerMethods.get(item);
            //获取方法上的注解，用 * 代替参数
            LoginNeedless method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), LoginNeedless.class);
            Optional.ofNullable(method).ifPresent(info -> Objects.requireNonNull(item.getPatternsCondition().getPatterns())
                    .forEach(url -> {
                     urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)); }));

            //获取类上的注解，用 * 代替参数
            LoginNeedless controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), LoginNeedless.class);
            Optional.ofNullable(controller).ifPresent(info -> Objects.requireNonNull(item.getPatternsCondition().getPatterns())
                    .forEach(url -> {
                        urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK));
                    })
            );
        });

        Optional.ofNullable(urls).ifPresent(info -> LoginNeedlessUtils.setLocal(urls));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public List<String> getUrls() {

        return this.urls;
    }
}
